package com.huangmb.anymark.app.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.*;
import com.amap.api.maps.model.*;
import com.huangmb.androidlib.utils.Logger;
import com.huangmb.androidlib.utils.PreferencesUtils;
import com.huangmb.anymark.app.R;
import com.huangmb.anymark.app.model.UserMarker;
import com.huangmb.anymark.app.utils.Locator;

import java.util.ArrayList;
import java.util.List;

/**
 * 需要使用高德地图的Fragment可以集成该类，该类维护着一个MapView的生命周期
 *
 * @author hmb
 * @version 1.0
 * @since 2016/4/16 14:12
 */
public class BaseMapFragment extends AppBaseFragment implements LocationSource,
        AMap.OnCameraChangeListener, AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener, Locator.LocationListener {

    private static final String TAG = "Map";
    protected MapView mMapView = null;
    protected AMap mAMap = null;
    private LatLng mLastPos;
    private final int IGNORE_CHANGE_DISTANCE = 50;//忽略的地图移动最小距离，当镜头移动距离小于该值的改变事件将被忽略
    private int mLastMoveDistance = 0;

    /**
     * 在onCreateView中实例化一个地图视图后需调用该方法
     *
     * @param mapView 地图
     * @param b       savedInstanceState
     */
    public void setUpMapView(MapView mapView, Bundle b) {
        this.mMapView = mapView;
        if (this.mMapView != null) {
            this.mAMap = this.mMapView.getMap();
            this.mMapView.onCreate(b);
            setDefaultMapSetting();
            LatLng pos = getPositionFromPreference();
            if (pos != null) {
                mAMap.moveCamera(CameraUpdateFactory.changeLatLng(pos));
            }
        }
    }

    public MapView getMapView() {
        return this.mMapView;
    }

    public AMap getAMap() {
        return this.mAMap;
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();
        }
    }

    private void setDefaultMapSetting() {
        if (this.mAMap == null) {
            return;
        }
        UiSettings ui = this.mAMap.getUiSettings();
        //允许显示定位按钮
        ui.setMyLocationButtonEnabled(true);

        mAMap.setMyLocationEnabled(true);
        mAMap.setLocationSource(this);
        mAMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        /*MyLocationStyle style = new MyLocationStyle();
        style.myLocationIcon(BitmapDescriptorFactory.fromResource(android.R.drawable.ic_menu_myplaces));
        style.radiusFillColor(Color.TRANSPARENT);
        style.strokeColor(Color.TRANSPARENT);
        mAMap.setMyLocationStyle(style);*/

        //隐藏缩放按钮
        ui.setZoomControlsEnabled(false);
        //显示指南针
        //ui.setCompassEnabled(true);
        //禁止手势旋转地图
        ui.setRotateGesturesEnabled(false);

        mAMap.setOnCameraChangeListener(this);
        mAMap.setOnMarkerClickListener(this);
        mAMap.setOnInfoWindowClickListener(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return true;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        Logger.d(TAG, "请求定位");


        Locator.startLocationOnce(this);
    }

    @Override
    public void deactivate() {
        Logger.d(TAG, "定位结束");
        Locator.stopLocation();
    }

    @Override
    public void onLocationChanged(@NonNull AMapLocation aMapLocation) {
        Logger.d(TAG, "定位成功" + aMapLocation.getLatitude() + "," + aMapLocation.getLongitude());
        LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14));
    }

    @Override
    public void onFail(AMapLocation aMapLocation) {
        toast(R.string.location_fail);
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (mLastPos != null) {
            mLastMoveDistance = (int) (AMapUtils.calculateLineDistance(mLastPos, cameraPosition.target));
            Logger.d(TAG, "本次移动距离" + mLastMoveDistance);
        }
        Logger.d(TAG, "onCameraChangeFinish");
        mLastPos = cameraPosition.target;
    }

    public boolean isNeedIgnoreCameraChange() {
        return mLastMoveDistance < IGNORE_CHANGE_DISTANCE;
    }


    protected void savePositionToPreference(LatLng pos) {
        if (pos != null) {
            PreferencesUtils.put(getContext(), "latitude", String.valueOf(pos.latitude));
            PreferencesUtils.put(getContext(), "longitude", String.valueOf(pos.longitude));
        }
    }

    protected LatLng getPositionFromPreference() {
        String lat = PreferencesUtils.getString(getContext(), "latitude", null);
        String lon = PreferencesUtils.getString(getContext(), "longitude", null);
        if (lat != null && lon != null) {
            try {

                double latitude = Double.valueOf(lat);
                double longitude = Double.valueOf(lon);
                return new LatLng(latitude, longitude);
            } catch (Exception e) {
                //
            }
        }
        return null;
    }

}
